<template>
	<div  :style="{height: divHeight}">
		<Form ref="form1" :model="formItem" :label-width="120">
            <Row class="query-form" style="padding-top: 15px">
                <Col span="8">
                    <FormItem label="公司名称：">
                        <Input class="query-form-el" v-model="formItem.orgName"></Input>
                    </FormItem>
                </Col>
                <Col span="8">
                    <FormItem label="组织机构级别：">
                        <Select filterable v-model="formItem.orgLevel"  @on-open-change="selectCodingSort"  >
                            <Option v-for="item in orgLevelList" :value="item.codingCodeId" :key="item.codingCodeId">{{ item.codingName }}</Option>
                        </Select>
                    </FormItem>
                </Col>
                <Col span="8">
                    <Button @click="reset" class="ivu-btn-reset">重置</Button>
                    <Button class="ivu-btn-query" icon="md-search" @click="query">查询</Button>
                </Col>
            </Row>
        </Form>

        <Table row-key='orgId' ref='table' :height="tableHeight" :loading="buttonLoading" class="table" no-data-text="没有查询到相关数据!"
               highlight-row stripe border :columns="orgColumn" :load-data="handleLoadData" width="100%" :data="orgDatas" size="small">
        </Table>
        <Modal v-model="value1" :transfer=false :width=900 :closable="false" :mask-closable="false"
               :title="tage?'组织机构修改':'组织机构添加'">
			<Form ref="formCustom" :model="formCustom" :rules="ruleCustom" :label-width="150" style="padding: 10px;">
				<Row>
				    <Col span="12">
						<FormItem label="组织机构名称：" prop="orgName">
							<div v-if="drawertitle==1">{{formCustom.orgName}}</div>
							<Input type="text" v-model="formCustom.orgName" v-else></Input>
						</FormItem>
				    </Col>
                    <Col span="12">
                        <FormItem label="组织机构简称：" prop="orgShortName">
                            <div v-if="drawertitle==1">{{formCustom.orgShortName}}</div>
                            <Input type="text" v-model="formCustom.orgShortName" v-else></Input>
                        </FormItem>
                    </Col>
                </Row>
                <Row>
				    <Col span="12">
						<FormItem label="上级组织机构：" prop="parentOrgName">
							 <div v-if="drawertitle==1">{{formCustom.parentOrgName}}</div>
                            <div v-else>
                                <Input readonly="" type="text" v-model="formCustom.parentOrgName"  ></Input>
                                <Input type="text" v-show="false" v-model="formCustom.parentId" ></Input>
                            </div>
						</FormItem>
				    </Col>
                    <Col span="12">
                        <FormItem label="法人代表：" prop="corporateRepresentative">
                            <div v-if="drawertitle==1">{{formCustom.corporateRepresentative}}</div>
                            <Input type="text" v-model="formCustom.corporateRepresentative" v-else></Input>
                        </FormItem>
                    </Col>
                </Row>
                <Row>
				    <Col span="12">
						<FormItem label="组织机构级别：" prop="orgLevel">
                            <div v-if="drawertitle==1">{{formCustom.orgLevel}}</div>
                            <Select v-else filterable v-model="formCustom.orgLevel"  @on-open-change="selectCodingSort"  >
                                <Option v-for="item in orgLevelList" :value="item.codingCodeId" :key="item.codingCodeId">{{ item.codingName }}</Option>
                            </Select>
						</FormItem>
				    </Col>
                    <Col span="12">
                        <FormItem label="组织机构类别：" prop="orgType">
                            <div v-if="drawertitle==1">{{formCustom.orgType}}</div>
                            <Select v-else filterable v-model="formCustom.orgType"  >
                                <Option v-for="item in orgTypeList" :value="item.codingCodeId" :key="item.codingCodeId">{{ item.codingName }}</Option>
                            </Select>
                        </FormItem>
                    </Col>
                </Row>
                <Row>
                    <Col span="12">
                        <FormItem label="管理单位：" prop="codeAffordIf">
                            <div v-if="drawertitle==1">{{formCustom.codeAffordIf=='1'?'是' : '否'}}</div>
                            <Select filterable v-model="formCustom.codeAffordIf"  v-else  >
                                <Option v-for="item in codeAffordIfList" :value="item.value" :key="item.value">{{ item.label }}</Option>
                            </Select>
                        </FormItem>
                    </Col>
				    <Col span="12">
						<FormItem label="行政区名称：" prop="canton">
							<div v-if="drawertitle==1">{{formCustom.canton}}</div>
							<Input type="text" v-model="formCustom.canton" v-else ></Input>
						</FormItem>
				    </Col>
                </Row>
                <Row>
				    <Col span="12">
						<FormItem label="行政区代码：" prop="cantonCode">
							<div v-if="drawertitle==1">{{formCustom.cantonCode}}</div>
							<Input type="text" v-model="formCustom.cantonCode" v-else ></Input>
						</FormItem>
				    </Col>
				    <Col span="12">
						<FormItem label="邮寄地址：" prop="address">
							<div v-if="drawertitle==1">{{formCustom.address}}</div>
							<Input type="text" v-model="formCustom.address" v-else ></Input>
						</FormItem>
				    </Col>
                </Row>
                <Row>
				    <Col span="12">
						<FormItem label="主页地址：" prop="homeUrl">
							<div v-if="drawertitle==1">{{formCustom.homeUrl}}</div>
							<Input type="text" v-model="formCustom.homeUrl" v-else ></Input>
						</FormItem>
				    </Col>
                </Row>
                <Row>
				    <Col span="24">
						<FormItem label="组织机构描述：" prop="orgDesc">
							<div v-if="drawertitle==1">{{formCustom.orgDesc}}</div>
							<Input type="textarea" :rows="4" v-model="formCustom.orgDesc" v-else ></Input>
						</FormItem>
				    </Col>
                </Row>
                <Row>
				    <Col span="24">
						<FormItem label="补充说明：" prop="remarks">
							<div v-if="drawertitle==1">{{formCustom.remarks}}</div>
							<Input type="textarea" :rows="4" v-model="formCustom.remarks" v-else ></Input>
						</FormItem>
				    </Col>
				</Row>
			</Form>
            <div slot="footer">
                <Button class='ivu-btn-save' @click="handleSubmit()">确定</Button>
                <Button type="text" class='ivu-btn-cancel' @click="cancel">取消</Button>
            </div>
		</Modal>
	</div>
</template>

<script>
	import {Api} from '../../../api/index.js'
    import {sessionStorage} from '../../../common/cacheUtils.js';

	export default {
		data() {
			return {
                formItem: {
                    orgName: "",
                    orgLevel:""
                },
                tableHeight: '',
                buttonLoading:false,
                tage : true,
                divHeight:220,
				orgDatas: [],
				value1: false,
                selectNodeInfo:{},
                selectNode:{},
                selectRoot:{},
                selectedOrg :{
				    orgId:'',
                    orgName:'',
                    orgCode:''
                },
				formCustom:{
					orgName :'',
					orgShortName :'',
                    parentOrgName :'',
                    parentOrgCode:'',
					corporateRepresentative :'',
					orgLevel :'',
					orgType :'',
					isFreezed :'是',
					forbidIf :'是',
					isEmptyOrg :'是',
					codeAffordIf :'1',
					canton :'',
					cantonCode :'',
					address :'',
					homeUrl :'',
					orgDesc :'',
					remarks :'',
                    parentOrgId :''
				},
				drawertitle:1,
				orgLevelList:[

				],
                orgLevelMap:{},
                orgTypeList:[
                    {
                       // codingCodeId : '0200100004000000005',
                      //  codingName : '机关'
                       codingCodeId : '1',
                       codingName : '公司级'
                    },{
                        codingCodeId : '0200100004000000006',
                        codingName : '生产单位'
                    }
				],
                codeAffordIfList :[
                    {
                        value : '1',
                        label  : '是'
                    },{
                        value : '0',
                        label  : '否'
                    }
                ],
                orgColumn:[
                    {
                        title: '组织机构名称',
                        minWidth: 200,
                        align: 'left',
                        key: 'orgName',
                        tree:true
                    },
                    {
                        title: '组织机构级别',
                        width: 150,
                        align: 'center',
                        key: 'orgLevel',
                        render:(h, params) => {
                            return h('span', this.orgLevelMap[params.row.orgLevel]);
                        }
                    },
                    {
                        title: '操作',
                        align: 'center',
                        width: 220,
                        render: (h, params) => {
                            return h('div', [
                                h('A', {
                                    props: { type: 'primary', size: 'small' },
                                    style: {
                                        fontSize: '14px'
                                    },
                                    on: {
                                        click: () => {
                                            this.viewOrgInfo(params.row);
                                        }
                                    }
                                }, '查看'),
                                h('Divider', {
                                    props: {
                                        type: 'vertical',
                                    }
                                }, ''),
                                h('A', {
                                    props: { type: 'primary', size: 'small' },
                                    style: {
                                        fontSize: '14px'
                                    },
                                    on: {
                                        click: () => {
                                            this.addOrgInfo(params.row);
                                        }
                                    }
                                }, '新增'),
                                h('Divider', {
                                    props: {
                                        type: 'vertical',
                                    }
                                }, ''),
                                h('A', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px'
                                    },
                                    on: {
                                        click: () => {
                                            this.modifyOrgInfo(params.row)
                                        }
                                    }
                                }, '修改'),
                                h('Divider', {
                                    props: {
                                        type: 'vertical',
                                    }
                                }, ''),
                                h('A', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px',
                                        color: 'red'
                                    },
                                    on: {
                                        click: () => {
                                            this.removeOrgInfo(params.row)   
                                        }
                                    }
                                }, '删除')
                            ]);
                        }
                    }
                ],
				ruleCustom: {
					orgName: [
                        { required: true, message: '  ', trigger: 'blur' }
                    ],
                    orgLevel: [
                        { required: true, message: '  ', trigger: 'change' }
                    ],
                    orgType: [
                        { required: true, message: '  ', trigger: 'change' }
                    ]
                }
			}
		},
		methods: {
            selectCodingSort(){
                this.$http.get(Api.queryCodeDetailBySortId +'/0200100005',{params:{}}).then((res) => {
                    this.orgLevelList = res.data.data;
                    this.orgLevelList.forEach(item=>{
                        this.orgLevelMap[item.codingCodeId] = item.codingName;
                    })
                })
            },
            handleLoadData (item, callback) {
                setTimeout(() => {
				    this.$http.get(Api.queryOrg, {
                        params: {
                            parentId: item.orgId,
                            codeAffordIf : 0
                        }
                    }).then(res => {
                        if(res.data.data.length !== 0) {
                            res.data.data.map(i => {
                                if(i.orgLevel != '0200100005000000007'){
                                    i._loading = false;
                                    i.children = [];
                                }
                            })
						    item.children = res.data.data;
                            callback(item.children);
                        } else {
                            delete item['_loading'];
                            item.children=[];
                            callback([]);
                        }
                    }).catch(e => {
                        console.log(e);
                        this.$Message.error('请求失败');
                    })
                }, 2000);
            },
            viewOrgInfo(orgInfo){
                this.drawertitle = 1;
                this.tage = true;
                this.$http.get(Api.queryOrgDetailById + "/" +orgInfo.orgId,{params:{}}).then(res => {
                    this.formCustom = res.data.data;
				}).catch(e => {
					this.$Message.error('请求失败');
				})
                this.value1 = true;
            },
            addOrgInfo(orgInfo){
                this.selectedOrg = orgInfo;
                this.drawertitle = 2;
                this.tage = false;
                this.formCustom = {};
                this.formCustom.parentOrgName = orgInfo.orgName;
                this.formCustom.parentId = orgInfo.orgId;
                this.formCustom.parentOrgCode = orgInfo.orgCode;
                this.value1 = true;
            },
            modifyOrgInfo(orgInfo){
                this.selectedOrg = orgInfo;
                this.drawertitle = 2;
                this.tage = true;
                this.$http.get(Api.queryOrgDetailById + "/" +orgInfo.orgId,{params:{}}).then(res => {
                    this.formCustom = res.data.data;
				}).catch(e => {
					this.$Message.error('请求失败');
				})
                this.value1 = true;
            },
			removeOrgInfo(orgInfo){
				this.$Modal.confirm({
                    title: '删除组织机构',
                    content: "此操作将不可恢复，是否删除",
                    onOk: () => {
                        this.$http.get(Api.queryOrg, {
                            params: {
                                parentId: orgInfo.orgId,
                                codeAffordIf : false
                            }
                        }).then(res => {
                            if(res.data.data.length !== 0) {
                                this.$Message.error('存在下级机构，不允许删除当前机构！');
                            } else {
                                this.$http.get(Api.deleteOrg + "/" +orgInfo.orgId, {
                                    params: {
                                    }
                                }).then(res => {
                                    this.orgDatas.forEach(item=>{
                                        this.removeChildren(item,orgInfo);
                                    })
                                }).catch(e => {
                                    console.log(e);
                                    this.$Message.error('请求失败');
                                })
                            }
                        }).catch(e => {
                            console.log(e);
                            this.$Message.error('请求失败');
                        })
                    },
                    onCancel: () => {
                        this.$Message.info('取消');
                    }
                });
				this.value1 = false
			},
            removeChildren(item,orgInfo){
                var i = 0;
                if(item.hasOwnProperty('children')){
                    item.children.forEach(item1=>{
                        if(item1.orgId == orgInfo.orgId){
                            item.children.splice(i, 1)
                            this.$Message.success('删除成功');
                            return;
                        }else{
                            this.removeChildren(item1,orgInfo);
                        }
                        i++;
                    })
                }
            },
            updateChildren(item,orgInfo){
                var i = 0;
                item.forEach(item1=>{
                    if(item1.orgId == orgInfo.orgId){
                        this.getOrgInfoTree(orgInfo.orgId,item1);
                        return;
                    }else{
                        if(item1.children != undefined)
                            this.updateChildren(item1.children,orgInfo);
                    }
                    i++;
                })
            },
			handleSubmit (name) {
                this.$refs['formCustom'].validate((valid) => {
                    if(valid) {
                        if(this.tage) {
                            this.$http.post(Api.updateOrg, this.formCustom).then(res => {
                                this.value1 = false
                                this.$Message.success('成功!');
                                this.$set(this.selectedOrg,"orgName",this.formCustom.orgName);
                                this.$set(this.selectedOrg,"orgLevel",this.formCustom.orgLevel);
                            }).catch(e => {
                                this.$Message.error('请求失败');
                            })
                        } else {
                            this.$http.post(Api.addOrg, this.formCustom).then(res => {
                                this.value1 = false
                                this.$Message.success('成功!');
                                this.updateChildren(this.orgDatas,this.selectedOrg);
                            }).catch(e => {
                                this.$Message.error('请求失败');
                            })
                        }
                    } else {
                        this.$Message.error('不能为空!');
                    }
                })
            },
            cancel (name) {
                this.value1 = false
            },
            getOrgInfo(){
                this.$http.get(Api.queryOrgDetailById + "/" + sessionStorage('userId').getObject('userId').companyId).then(res => {
                    this.orgDatas = [];
                    var temp = {};
                    temp._loading = false;
                    temp.children = [];
                    temp.orgName = res.data.data.orgName;
                    temp.orgId = res.data.data.orgId;
                    this.orgDatas.push(temp);
				}).catch(e => {
					this.$Message.error('请求失败');
				})
            },
            getOrgInfoTree(orgId,currentOrgInfo){
            	this.$http.get(Api.queryOrg, {
					params: {
                        parentId: orgId,
                        codeAffordIf : 0
					}
				}).then(res => {
					res.data.data.map(i => {
                        if(i.orgLevel != '0200100005000000007'){
                            i._loading = false;
                            i.children = [];
                        }
					})
                    if(orgId == "-1"){
                        this.orgDatas = [];
                        this.orgDatas.push(res.data.data[0]);
                    }else{
                        this.$set(currentOrgInfo,'children',res.data.data);
                        this.$set(currentOrgInfo,'_showChildren',true);
                        delete currentOrgInfo['_loading'];
                    }
				}).catch(e => {
					this.$Message.error('请求失败');
				})
            },
            reset(){
                this.formItem.userName = '';
                this.formItem.orgLevel = '';
                this.getOrgInfo();
            },
            query(){
                this.$http.get(Api.queryOrgList+"?orgName="+this.formItem.orgName+"&fromPage=1&pageSize=1000").then(res => {
                    var datas = [];
                    res.data.data.map(i => {
                        if(this.formItem.orgLevel != ''&&i.orgLevel != this.formItem.orgLevel){
                            return;
                        }
                        if(i.orgLevel != '0200100005000000007'){
                            i._loading = false;
                            i.children = [];
                        }
                        datas.push(i);
                    })
                    this.orgDatas = datas;
                }).catch(e => {
					this.$Message.error('请求失败');
				})
            },
		},
		mounted() {
            this.divHeight = (window.innerHeight - 120) + 'px';
             this.tableHeight = window.innerHeight - this.$refs.table.$el.offsetTop - 100;
            this.selectCodingSort();
			this.getOrgInfo();
		},
		components: {
		}
	}
</script>
<style lang='css' scoped>
    @import '../../../index.css';

</style>